package com.lsy.controller.back;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lsy.entity.ProductCustom;
import com.lsy.service.interf.ProductService;

@Controller
@RequestMapping("/back/product")
public class ProductController {

	@Autowired
	private ProductService productService;

	@RequestMapping("/queryProduct")
	public ModelAndView queryProduct() throws Exception {

		// 商品列表
		List<ProductCustom> productsList = productService.findproductList(null);

		// 创建modelAndView准备填充数据、设置视图
		ModelAndView modelAndView = new ModelAndView();

		// 填充数据
		modelAndView.addObject("productsList", productsList);

		// 指定视图
		modelAndView.setViewName("/BackEnd/productsList");

		return modelAndView;

	}

	@RequestMapping("/queryById")
	@ResponseBody
	public ProductCustom queryById(int id) {
		ProductCustom product = null;
		try {
			product = productService.findProductById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return product;
	}

	@RequestMapping(path = "/addProduct", params = "action=form")
	public String addProdcut() {
		return "/BackEnd/addProduct";
	}

	@RequestMapping("/addProduct")
	@ResponseBody
	public String addProduct(ProductCustom product) {
		String result = "{\"code\":\"fail\"}";
		try {
			product.setPpubtime(new Date());
			productService.save(product);
			result = "{\"code\":\"success\"}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(int id) {
		String result = "{\"code\":\"fail\"}";
		try {
			productService.delete(id);
			result = "{\"code\":\"success\"}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/update")
	@ResponseBody
	public String update(ProductCustom product) {
		String result = "{\"code\":\"fail\"}";
		try {
			productService.update(product);
			result = "{\"code\":\"success\"}";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
